import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {TableUtil} from "../../../../util/table-util";
import {ResponseUtil} from "../../../../util/response-util";
import {TemplateAPI} from "../../template-constants";
import {OneOperationComponent} from "../../../../widgets/one-operation/one-operation.component";
import {ActivatedRoute, Router} from "@angular/router";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {TplManageService} from "./tpl-manage.service";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";

declare var $;

@Component({
  selector: 'app-tpl-manage',
  templateUrl: './tpl-manage.component.html',
  styleUrls: ['./tpl-manage.component.css']
})
export class TplManageComponent implements OnInit,AfterViewInit {
@ViewChild(OneOperationComponent) operation:OneOperationComponent;

  id:Array<string> = [];

  table

  constructor(
    private router:Router,
    private route:ActivatedRoute,
    private tableUtil: TableUtil,
    private responseUtil: ResponseUtil,
    private tplManageService: TplManageService,
    private dialogService: OneDialogService,
    private pageSubject: PageSubject
  ) { }

  ngOnInit() {
    this.pushPage();
    this.loadTemplateTable()
  }

  ngAfterViewInit(){
    this.operation.proxy = this.proxy;
  }

  proxy={
    'reportTemplateAdd':()=>this.reportTemplateAdd(),
    'reportTemplateUpdate':()=>this.reportTemplateUpdate(),
    'reportTemplateDele':()=>this.reportTemplateDele(),
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path('模板', '');
    this.pageSubject.pushPage('模板管理', '', path);
  }


  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 模板列表查询
   */
  loadTemplateTable() {
    this.table = this.tableUtil.load("one_table_template",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "name", title: '名称', align: 'left'},
        {field: "code", title: '编码', align: 'left'},
        {field: "srcPath", title: '存储路径'},
        {field: "description", title: '描述' ,align: 'middle' },
        {field: "remark", title: '备注' , align: 'middle' },
        {field: "type", title: '类型', align: 'left', width:'50',formatter:this.typeFormat},
        {field: "isUse", title: '启用', align: 'left', width:'50', formatter:this.yesOrNoFormat},
        {field: "creator", title: '创建人', align: 'left', visible: false},
        {field: "createDate", title: '创建日期', align: 'left', sortName: "CREATE_DATE", sortable: true, visible: false},
        {field: "updator", title: '修改人', align: 'left',visible: false},
        {field: "updateDate", title: '修改日期', align: 'left', sortName: "UPDATE_DATE", sortable: true, visible:false}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_tpl-manage",
      url:TemplateAPI.templatePageListV2 ,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#templateName").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.creator = value.UPDATORNAME || '';
            value.updator = value.UPDATORNAME || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: 'UPDATE_DATE',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true ,//响应式
    });

    this.tableUtil.bindResetTableView(this.table);
  }
  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private typeFormat(value, row, index) {
    if (value == '1') {
      return '正式';
    }
    if (value == '0') {
      return '测试';
    }
  }

  /**
   * 模板添加操作
   */
  private reportTemplateAdd(){
      this.router.navigate(['add'],{relativeTo:this.route})
  }

  /**
   * 模板修改方法
   * 1.判断是否选择数据
   * 2.获取id，并判断id长度是否为'1'
   * 3.长度为'1'时，进行跳转，否则提示
   * @returns {any}
   */
  private reportTemplateUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo("请选择一条数据!");
    }
   this.id = this.tableUtil.getIds(rows);
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['update', {id: this.id[0]}], {relativeTo: this.route})
    }
  }

  /**
   * 模板删除方法
   * 1.判断是否选择数据
   * 2.获取id，并判断id长度是否为'0'
   * 3.长度为'0时，进行提示，否则执行删除方法
   * @returns {any}
   */
  private reportTemplateDele(){
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo("请选择一条数据!");
    }
    this.id = this.tableUtil.getIds(rows);
    if (this.id.length == 0) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.templateDeletesMothod);
    }
  }

  templateDeletesMothod =()=>{
    //调用后端接口
    if (this.id.length != 0) {
      this.tplManageService.templateDeletes(this.id).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    }else{
      this.dialogService.modalInfo("请选择一条数据");
    }
  }

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }



}
